﻿namespace Hidistro.UI.Web.Admin.sales
{
    using ASPNET.WebControls;
    using Hidistro.ControlPanel.Sales;
    using Hidistro.Core;
    using Hidistro.Entities;
    using Hidistro.Entities.Orders;
    using Hidistro.Entities.Promotions;
    using Hidistro.Entities.Sales;
    using Hidistro.Membership.Context;
    using Hidistro.Membership.Core;
    using Hidistro.Messages;
    using Hidistro.UI.Common.Controls;
    using Hidistro.UI.ControlPanel.utility;
    using Hishop.Plugins;
    using System;
    using System.Net;
    using System.Web.UI.WebControls;

    public class BatchSendOrderGoods : AdminPage
    {
        protected Button btnBatchSendGoods;
        protected Button btnSetShipOrderNumber;
        protected Button btnSetShippingMode;
        protected DropdownColumn dropExpress;
        protected DropDownList dropExpressComputerpe;
        protected DropdownColumn dropShippId;
        protected ShippingModeDropDownList dropShippingMode;
        protected Grid grdOrderGoods;
        private string strIds;
        protected TextBox txtStartShipOrderNumber;

        private void BindData()
        {
            DropdownColumn column = (DropdownColumn) this.grdOrderGoods.Columns[4];
            column.DataSource = SalesHelper.GetShippingModes();
            DropdownColumn column2 = (DropdownColumn) this.grdOrderGoods.Columns[5];
            column2.DataSource = ExpressHelper.GetAllExpress();
            string orderIds = "'" + this.strIds.Replace(",", "','") + "'";
            this.grdOrderGoods.DataSource = OrderHelper.GetSendGoodsOrders(orderIds);
            this.grdOrderGoods.DataBind();
        }

        private void btnSendGoods_Click(object sender, EventArgs e)
        {
            if (this.grdOrderGoods.Rows.Count <= 0)
            {
                this.ShowMsg("没有要进行发货的订单。", false);
                return;
            }
            DropdownColumn dropdownColumn = (DropdownColumn)this.grdOrderGoods.Columns[4];
            ListItemCollection selectedItems = dropdownColumn.SelectedItems;
            DropdownColumn dropdownColumn2 = (DropdownColumn)this.grdOrderGoods.Columns[5];
            ListItemCollection selectedItems2 = dropdownColumn2.SelectedItems;
            int num = 0;
            for (int i = 0; i < selectedItems.Count; i++)
            {
                string orderId = (string)this.grdOrderGoods.DataKeys[this.grdOrderGoods.Rows[i].RowIndex].Value;
                TextBox textBox = (TextBox)this.grdOrderGoods.Rows[i].FindControl("txtShippOrderNumber");
                ListItem listItem = selectedItems[i];
                ListItem listItem2 = selectedItems2[i];
                int num2 = 0;
                int.TryParse(listItem.Value, out num2);
                if (!string.IsNullOrEmpty(textBox.Text.Trim()) && !string.IsNullOrEmpty(listItem.Value) && int.Parse(listItem.Value) > 0 && !string.IsNullOrEmpty(listItem2.Value))
                {
                    OrderInfo orderInfo = OrderHelper.GetOrderInfo(orderId);
                    if ((orderInfo.GroupBuyId <= 0 || orderInfo.GroupBuyStatus == GroupBuyStatus.Success) && ((orderInfo.OrderStatus == OrderStatus.WaitBuyerPay && orderInfo.Gateway == "hishop.plugins.payment.podrequest") || orderInfo.OrderStatus == OrderStatus.BuyerAlreadyPaid) && num2 > 0 && !string.IsNullOrEmpty(textBox.Text.Trim()) && textBox.Text.Trim().Length <= 20)
                    {
                        ShippingModeInfo shippingMode = SalesHelper.GetShippingMode(num2, true);
                        orderInfo.RealShippingModeId = shippingMode.ModeId;
                        orderInfo.RealModeName = shippingMode.Name;
                        ExpressCompanyInfo expressCompanyInfo = ExpressHelper.FindNode(listItem2.Value);
                        orderInfo.ExpressCompanyName = expressCompanyInfo.Name;
                        orderInfo.ExpressCompanyAbb = expressCompanyInfo.Kuaidi100Code;
                        orderInfo.ShipOrderNumber = textBox.Text;
                        if (OrderHelper.SendGoods(orderInfo))
                        {
                            SendNoteInfo sendNoteInfo = new SendNoteInfo();
                            sendNoteInfo.NoteId = Globals.GetGenerateId() + num;
                            sendNoteInfo.OrderId = orderId;
                            sendNoteInfo.Operator = HiContext.Current.User.Username;
                            sendNoteInfo.Remark = "后台" + sendNoteInfo.Operator + "发货成功";
                            OrderHelper.SaveSendNote(sendNoteInfo);
                            if (!string.IsNullOrEmpty(orderInfo.GatewayOrderId) && orderInfo.GatewayOrderId.Trim().Length > 0)
                            {
                                PaymentModeInfo paymentMode = SalesHelper.GetPaymentMode(orderInfo.Gateway);
                                if (paymentMode != null)
                                {
                                    PaymentRequest paymentRequest = PaymentRequest.CreateInstance(paymentMode.Gateway, HiCryptographer.Decrypt(paymentMode.Settings), orderInfo.OrderId, orderInfo.GetTotal(), "订单发货", "订单号-" + orderInfo.OrderId, orderInfo.EmailAddress, orderInfo.OrderDate, Globals.FullPath(Globals.GetSiteUrls().Home), Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("PaymentReturn_url", new object[]
							{
								paymentMode.Gateway
							})), Globals.FullPath(Globals.GetSiteUrls().UrlData.FormatUrl("PaymentNotify_url", new object[]
							{
								paymentMode.Gateway
							})), "");
                                    paymentRequest.SendGoods(orderInfo.GatewayOrderId, orderInfo.RealModeName, orderInfo.ShipOrderNumber, "EXPRESS");
                                }
                            }
                            if (!string.IsNullOrEmpty(orderInfo.TaobaoOrderId))
                            {
                                try
                                {
                                    string requestUriString = string.Format("http://order2.kuaidiangtong.com/UpdateShipping.ashx?tid={0}&companycode={1}&outsid={2}&Host={3}", new object[]
							{
								orderInfo.TaobaoOrderId,
								expressCompanyInfo.TaobaoCode,
								orderInfo.ShipOrderNumber,
								HiContext.Current.SiteUrl
							});
                                    WebRequest webRequest = WebRequest.Create(requestUriString);
                                    webRequest.GetResponse();
                                }
                                catch
                                {
                                }
                            }
                            int num3 = orderInfo.UserId;
                            if (num3 == 1100)
                            {
                                num3 = 0;
                            }
                            IUser user = Users.GetUser(num3);
                            Messenger.OrderShipping(orderInfo, user);
                            orderInfo.OnDeliver();
                            num++;
                        }
                    }
                }
            }
            if (num == 0)
            {
                this.ShowMsg("批量发货失败！", false);
                return;
            }
            if (num > 0)
            {
                this.BindData();
                this.ShowMsg(string.Format("批量发货成功！发货数量{0}个", num), true);
            }
        }

        private void btnSetShipOrderNumber_Click(object sender, EventArgs e)
        {
            string orderIds = this.GetOrderIds();
            string[] strArray = orderIds.Split(new char[] { ',' });
            long result = 0L;
            string str2 = "'" + orderIds.Replace(",", "','") + "'";
            if (!string.IsNullOrEmpty(this.dropExpressComputerpe.SelectedValue))
            {
                OrderHelper.SetOrderExpressComputerpe(str2, this.dropExpressComputerpe.SelectedItem.Text, this.dropExpressComputerpe.SelectedValue);
            }
            if (!string.IsNullOrEmpty(this.txtStartShipOrderNumber.Text.Trim()) && long.TryParse(this.txtStartShipOrderNumber.Text.Trim(), out result))
            {
                try
                {
                    OrderHelper.SetOrderShipNumber(strArray, this.txtStartShipOrderNumber.Text.Trim(), this.dropExpressComputerpe.SelectedValue);
                    this.BindData();
                }
                catch (Exception)
                {
                    this.ShowMsg("你输入的起始单号不正确", false);
                }
            }
            else
            {
                this.ShowMsg("起始发货单号不允许为空且必须为正整数", false);
            }
        }

        private void btnSetShippingMode_Click(object sender, EventArgs e)
        {
            string orderIds = this.GetOrderIds();
            string str2 = "'" + orderIds.Replace(",", "','") + "'";
            if (this.dropShippingMode.SelectedValue.HasValue)
            {
                OrderHelper.SetOrderShippingMode(str2, this.dropShippingMode.SelectedValue.Value, this.dropShippingMode.SelectedItem.Text);
            }
            this.BindData();
        }

        protected string GetOrderIds()
        {
            string str = string.Empty;
            for (int i = 0; i < this.grdOrderGoods.Rows.Count; i++)
            {
                GridViewRow row1 = this.grdOrderGoods.Rows[i];
                str = str + this.grdOrderGoods.DataKeys[i].Value.ToString() + ",";
            }
            return str.TrimEnd(new char[] { ',' });
        }

        private void grdOrderGoods_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                string orderId = (string) this.grdOrderGoods.DataKeys[e.Row.RowIndex].Value;
                DropDownList list = e.Row.FindControl("dropExpress") as DropDownList;
                OrderInfo orderInfo = OrderHelper.GetOrderInfo(orderId);
                if ((orderInfo != null) && (orderInfo.OrderStatus == OrderStatus.BuyerAlreadyPaid))
                {
                    ExpressCompanyInfo info2 = ExpressHelper.FindNode(orderInfo.ExpressCompanyName);
                    if (info2 != null)
                    {
                        list.SelectedValue = info2.Kuaidi100Code;
                    }
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.strIds = base.Request.QueryString["OrderIds"];
            this.btnSetShippingMode.Click += new EventHandler(this.btnSetShippingMode_Click);
            this.btnSetShipOrderNumber.Click += new EventHandler(this.btnSetShipOrderNumber_Click);
            this.grdOrderGoods.RowDataBound += new GridViewRowEventHandler(this.grdOrderGoods_RowDataBound);
            this.btnBatchSendGoods.Click += new EventHandler(this.btnSendGoods_Click);
            if (!this.Page.IsPostBack)
            {
                this.dropShippingMode.DataBind();
                this.dropExpressComputerpe.DataSource = ExpressHelper.GetAllExpress();
                this.dropExpressComputerpe.DataTextField = "Name";
                this.dropExpressComputerpe.DataValueField = "Name";
                this.dropExpressComputerpe.DataBind();
                this.dropExpressComputerpe.Items.Insert(0, new ListItem("", ""));
                this.BindData();
            }
        }
    }
}

